# views/analysis_view/controller.py
from PyQt6.QtWidgets import QFileDialog
import pandas as pd
from models.data_model import DataModel  # 数据模型解耦
from utils.file_utils import validate_file  # 复用工具类


class DataAnalysisController:
	def __init__(self, view):
		self.view = view
		self.current_file = None
		self.connect_signals()
	
	def connect_signals(self):
		"""连接信号与槽"""
		self.view.btn_select.clicked.connect(self.select_file)
		self.view.btn_analyze.clicked.connect(self.analyze_data)
	
	def select_file(self):
		"""处理文件选择"""
		file_path, _ = QFileDialog.getOpenFileName(
			self.view, "选择文件", "", "Excel Files (*.xlsx)"
		)
		if validate_file(file_path):  # 调用工具类校验文件
			self.current_file = file_path
			self.view.file_label.setText(f"已选择: {file_path}")
			self.view.btn_analyze.setEnabled(True)
	
	def analyze_data(self):
		"""执行数据分析"""
		if not self.current_file:
			return
		
		# 通过数据模型处理
		df = DataModel.load_file(self.current_file)
		analysis_result = DataModel.analyze(df)
		
		# 触发图表生成
		self.generate_chart(analysis_result)
	
	def generate_chart(self, data):
		"""生成图表并发送到历史模块"""
		chart = DataModel.create_chart(data)
		self.view.parent().chart_list_page.add_chart(chart)  # 与主窗口交互
